package com.epfresh.api.update;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.R;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.permission.HiPermission;
import com.epfresh.api.permission.PermissionCallback;
import com.epfresh.api.utils.NetworkUtil;

import java.io.File;

//import com.epfresh.api.global.AppApplication;

/**
 * Created by Administrator on 2016/6/16.
 */
public class UpdateApkDialogActivity extends AppCompatActivity {

    Context context = this;
    private String appUrl = "";

    private boolean isForceUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        appUrl = getIntent().getStringExtra(Constants.APK_DOWNLOAD_URL);
                        if (appUrl == null || "".equals(appUrl)) {
                            finish();
                        } else {
                            showUpdateDialog(false);
                        }
                    }
                });
            }
        }.start();

        if (savedInstanceState != null) {
            getIntent().putExtra("isForceUpdate", savedInstanceState.getBoolean("isForceUpdate"));
        }
        ApplicationHelper.isUpdateActivityAlive = true;
        ApplicationHelper.updateApkDialogActivity = this;
        isForceUpdate = getIntent().getBooleanExtra("isForceUpdate", true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        boolean isForce = getIntent().getBooleanExtra("isForceUpdate", true);
        if (!isForceUpdate) {
            isForceUpdate = isForce;
        }
        if (dialog != null && btnNegative != null) {
            if (isForceUpdate) {
                dialog.setCanceledOnTouchOutside(false);
                btnNegative.setVisibility(View.GONE);
            } else {
                dialog.setCanceledOnTouchOutside(true);
                btnNegative.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isForceUpdate", isForceUpdate);
        super.onSaveInstanceState(outState);
    }

    Dialog dialog;
    TextView btnNegative;
    TextView btnPositive;
    TextView btnMid;
    TextView tvContent;

    /**
     * 显示软件更新对话框
     */
    private void showUpdateDialog(final boolean isDownLoadFail) {

        try {
            if (dialog == null) {
                dialog = new Dialog(this, R.style.custom_dialog);
                dialog.setContentView(R.layout.dialog_update);
                btnNegative = (TextView) dialog.findViewById(R.id.negativeButton);
                btnPositive = (TextView) dialog.findViewById(R.id.positiveButton);
                btnMid = (TextView) dialog.findViewById(R.id.tv_mid);
                tvContent = (TextView) dialog.findViewById(R.id.message);
                btnNegative.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isForceUpdate) {
                            dialog.dismiss();
                        }
                    }
                });
                btnPositive.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (ApplicationHelper.isDownloadApkFail) {
                            openWeb();
                            if (!isForceUpdate) {
                                dialog.dismiss();
                            } else {

                            }
                            return;
                        }
                        HiPermission.create(UpdateApkDialogActivity.this).checkSinglePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                            @Override
                            public void onClose() {

//                                T.toast("onClose");
                            }

                            @Override
                            public void onFinish() {
                                goToDownload();
                                if (!isForceUpdate) {
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                    showDownloadDialog();
                                }
//                                T.toast("onFinish");
                            }

                            @Override
                            public void onDeny(String permisson, int position) {
//                                T.toast("onDeny");
                                openWeb();
                            }

                            @Override
                            public void onGuarantee(String permisson, int position) {
//                                T.toast("onGuarantee");
                                goToDownload();
                                if (!isForceUpdate) {
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                    showDownloadDialog();
                                }
                            }
                        });


                    }
                });
                btnMid.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            openWeb();
                        }
                });
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                            if (isForceUpdate) {
                                intoHome();
                                return true;
                            }

                        }
                        return false;
                    }
                });

                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (!isForceUpdate) {
                            dialog.cancel();
                            new Thread() {
                                public void run() {
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            finish();
                                        }
                                    });
                                }
                            }.start();
                        }
                    }
                });

            }
            if (NetworkUtil.isWifi(this)) {
                if (isForceUpdate) {
                    tvContent.setText("检测到新版本，请更新！");
                } else {
                    tvContent.setText(R.string.soft_update_info);
                }
            } else {
                tvContent.setText(R.string.soft_update_mobile_net);
            }

            if (isDownLoadFail) {//下载失败
                tvContent.setText("重新下载");
            }

            if (isDownLoadFail || ApplicationHelper.isDownloadApkFail) {
                btnPositive.setVisibility(View.GONE);
            }else {
                btnPositive.setVisibility(View.VISIBLE);
            }
            if (isForceUpdate) {
                dialog.setCanceledOnTouchOutside(false);
                btnNegative.setVisibility(View.GONE);
            } else {
                dialog.setCanceledOnTouchOutside(true);
                btnNegative.setVisibility(View.VISIBLE);
            }
            dialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openWeb(){
        Intent intent= new Intent();

        intent.setAction(Intent.ACTION_VIEW);

//        Uri content_url = Uri.parse(Constant.URL_SHARE_DOWNLOAD);
        Uri content_url = Uri.parse(appUrl);

        intent.setData(content_url);

        startActivity(Intent.createChooser(intent, "下载app"));
    }

    private ProgressBar mProgress; // 进度条 结果
    private TextView result;
    private TextView tvTitle;
    private TextView tvInstall;
    private Dialog mDownloadDialog;
    private File apkFile;
    private int progressInt = 0;

    private void showDownloadDialog() {

        if (mDownloadDialog == null) {
            mDownloadDialog = new Dialog(this, R.style.custom_dialog);
            mDownloadDialog.setContentView(R.layout.dialog_update_progress);
            mProgress = (ProgressBar) mDownloadDialog.findViewById(R.id.update_progress);
            result = (TextView) mDownloadDialog.findViewById(R.id.result);
            tvTitle = (TextView) mDownloadDialog.findViewById(R.id.tv_title);
            tvInstall = (TextView) mDownloadDialog.findViewById(R.id.tv_install);
            mDownloadDialog.setCancelable(false);
            mDownloadDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        if (isForceUpdate && progressInt > 99) {
                            mDownloadDialog.dismiss();
                            finish();
                            return true;
                        }

                    }
                    return false;
                }
            });

            tvInstall.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
/*                    if (apkFile != null && apkFile.exists()) {
                        Intent installAPKIntent = new Intent(Intent.ACTION_VIEW);
                        //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
                        String[] command = {"chmod", "777", apkFile.toString()};
                        installAPKIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        installAPKIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        //installAPKIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        //installAPKIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        startActivity(installAPKIntent);
                    }*/
                    if (apkFile != null && apkFile.exists()) {
                        Log.e("activity_install","activity_install");
                        Intent installAPKIntent = new Intent(Intent.ACTION_VIEW);
                        //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
                        String[] command = {"chmod", "777", apkFile.toString()};
                        try {
                            ProcessBuilder builder = new ProcessBuilder(command);
                            builder.start();
                        }
                            catch (Exception e) {
                                Log.e("UpdateApk", "download apk file error", e);
                                e.printStackTrace();
                            } finally {}

///*                        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
//                            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
//                            Uri apkUri =
//                                    FileProvider.getUriForFile(context, context.getPackageName(), apkFile);
//                            //添加这一句表示对目标应用临时授权该Uri所代表的文件
//                            installAPKIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                            installAPKIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//                        }else{*/
//                            installAPKIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//                            installAPKIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                      //  }
//                        startActivity(installAPKIntent);
                        install(apkFile);
                    }


                }
            });

        }
        if (progressInt > 99) {
            tvInstall.setVisibility(View.VISIBLE);
        } else {
            tvInstall.setVisibility(View.GONE);
        }
        mDownloadDialog.show();
    }

    public void install(File file) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context,  ApplicationHelper.getInstance().getFileProvider(), file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }else{
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");



            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);




        }
        startActivity(intent);
    }

    public void setFileApk(File apkFile) {
        this.apkFile = apkFile;
    }


    private void goToDownload() {
        Intent intent = new Intent(getApplicationContext(), DownloadService.class);
        intent.putExtra(Constants.APK_DOWNLOAD_URL, appUrl);
        startService(intent);
    }

    protected void intoHome() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    public void updateProgress(final int progress) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDownloadDialog != null && mProgress != null && result != null && tvTitle != null) {
                    mProgress.setProgress(progress);
                    result.setText((progress < 0 ? 0 : progress) + "%");
                    progressInt = progress;
                    if (progress > 99) {
                        tvInstall.setVisibility(View.VISIBLE);
                        tvTitle.setText("下载完成");
                    } else if (progress > -1) {
                        tvInstall.setVisibility(View.GONE);
                        tvTitle.setText("正在下载新版本...");
                    } else {//下载失败
                        mDownloadDialog.dismiss();
                        showUpdateDialog(true);
                        tvInstall.setVisibility(View.GONE);

                    }

                }
            }
        });


    }


    @Override
    protected void onDestroy() {
        ApplicationHelper.isUpdateActivityAlive = false;
        ApplicationHelper.updateApkDialogActivity = null;
        super.onDestroy();
        if (isForceUpdate && progressInt > 99) {
            System.runFinalizersOnExit(true);
            System.exit(0);
        }
    }


//    private long exitTime = 0; // 系统退出时间
//
//    @Override
//    public void onBackPressed() {
//
//        if (System.currentTimeMillis() - exitTime > 2000) {
//            T.toast("再按一次返回键，退出程序");
//            exitTime = System.currentTimeMillis();
//        } else {
//            super.onBackPressed();
//        }
//    }

}
